package com.exposit.zbs.controller;

import com.exposit.zbs.model.GrantApplication;
import com.exposit.zbs.model.GrantApplicationStatus;
import com.exposit.zbs.model.User;
import com.exposit.zbs.service.IGrantApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.xml.ws.http.HTTPException;


/**
 * Created by Andrey on 19.08.2014.
 */
@Controller
@RequestMapping("/admin")
public class AdminAjaxController {

	@Autowired
	IGrantApplicationService grantApplicationService;

	@RequestMapping(value = "/grant/accept/{grantId}", method = RequestMethod.GET)
	@ResponseBody
	public String acceptGrant(@PathVariable String grantId, @PathVariable("grantId") GrantApplication grantApplication, HttpSession session) {

		Object currentUserObject = session.getAttribute("sessionUser");
		if (currentUserObject != null && currentUserObject instanceof User) {
			User currentUser = (User) currentUserObject;
			if (currentUser.getRole().getRoleName().equals("ROLE_ADMIN")) {
				grantApplication.setGrantApplicationStatus(new GrantApplicationStatus(new Long(2), "ACCEPTED"));
				grantApplicationService.updateGrant(grantApplication);
			} else {
				throw new HTTPException(400);
			}
		}

		return "OK";
	}

	@RequestMapping(value = "/grant/refuse/{grantId}", method = RequestMethod.GET)
	@ResponseBody
	public String refusetGrant(@PathVariable String grantId, @PathVariable("grantId") GrantApplication grantApplication, HttpSession session) {
		//TODO Check is admin
		grantApplication.setGrantApplicationStatus(new GrantApplicationStatus(new Long(3), "REFUSED"));
		grantApplication.setReviewDate(new java.util.Date());
		grantApplicationService.updateGrant(grantApplication);
		return "OK";
	}
}
